package com.gcit.seniorWish.web.modular.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gcit.seniorWish.web.core.exception.BizExceptionEnum;
import com.gcit.seniorWish.web.common.persistence.dao.DictMapper;
import com.gcit.seniorWish.web.common.persistence.model.Dict;
import com.gcit.seniorWish.core.exception.GunsException;
import com.gcit.seniorWish.web.modular.system.dao.DictDao;
import com.gcit.seniorWish.web.modular.system.service.IDictService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

@Service("dictService")
@Transactional
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements IDictService {

    @Resource
    DictDao dictDao;

    @Resource
    DictMapper dictMapper;
    
    /**
    * 添加字典
    * @param pDict 父级字典
    * @param subDictList 子字典列表
    * @author gaozhichang
    * @date 2018-03-15 上午 9:22
    */
    @Override
    public void addDict(Dict pDict, List<Dict> subDictList) {
        //判断有没有该字典
        if(baseMapper.selectCount(Condition.create().eq("code",pDict.getCode()).ne("id",pDict.getId()))>0){
            throw new GunsException(BizExceptionEnum.DICT_EXISTED);
        }
        //设置父级字典的pid固定为0
        pDict.setPid("0");
        baseMapper.insert(pDict);
        for (Dict subDict : subDictList) {
            subDict.setPid(pDict.getId());
            subDict.setPcode(pDict.getCode());
        }
        if(subDictList.size()>0){
            this.insertBatch(subDictList);
        }
    }

    @Override
    public void editDict(Dict pDict, List<Dict> subDictList) {
        baseMapper.updateById(pDict);

        List<Dict> insertList = new LinkedList<>();
        Iterator<Dict> it =subDictList.iterator();
        while (it.hasNext()) {
            Dict next =  it.next();
            next.setPcode(pDict.getCode());
            if(StrUtil.isBlank(next.getId())){
                insertList.add(next);
                it.remove();
            }
        }
        if(insertList.size()>0){
            this.insertBatch(insertList);
        }
        this.updateBatchById(subDictList);
    }

    /**
     * 删除字典
     *
     * @param dictId 字典id
     * @author gaozhichang
     * @date 2018年03月13日 21:23
     */
    @Override
    public void deleteDict(String dictId) {
        //删除这个字典的子词典
        Wrapper<Dict> dictEntityWrapper = new EntityWrapper<>();
        dictEntityWrapper = dictEntityWrapper.eq("pid", dictId);
        dictMapper.delete(dictEntityWrapper);
        //删除这个词典
        dictMapper.deleteById(dictId);
    }
}
